<?php

namespace backend\models;

use Yii;
use common\models\UserInfo;
use yii\helpers\ArrayHelper;
use yii\db\ActiveRecord;
use backend\models\Qr;

/**
 * This is the model class for table "sys_item".
 *
 * @property integer $id
 * @property integer $type
 * @property string $name
 * @property integer $img_small_id
 * @property integer $img_thumb_id
 * @property integer $img_url_id
 * @property string $tips
 * @property string $price_base
 * @property string $price_discount
 * @property string $price_cost
 * @property string $fabric_list
 * @property string $material_list
 * @property string $related_list
 * @property integer $app_return
 * @property integer $class_id
 * @property integer $brand_id
 */
class SysItem extends \yii\db\ActiveRecord
{
	public $class1;
	public $class2;

	public $color_list;
	public $style_list;
	public $space_list;
	public $price_list;
	public $place_list;
	public $sery_list;

	public $price_batch;
	public $price_batch_all;
	public $brand_id_for_price;
	public $brand_head;//品牌
	public $bread_head;//品牌类别
	public $unit_name;
	public $brandname;
	public $classname;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sys_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'img_small_id', 'img_thumb_id', 'img_url_id', 'app_return', 'class_id', 'brand_id','class2','price_batch_all','top_time','min_order_quantity','unit_id'], 'integer'],
            [['price_base', 'price_discount','volume','state_tree'], 'number'],

            [['name'], 'string', 'max' => 64],
            [['introduction'], 'string', 'max' => 40],
            [['tips'], 'string', 'max' => 4096],
            [['fabric_list', 'material_list', 'related_list'], 'string', 'max' => 128],
            [['price_base', 'price_discount', 'price_batch'],'double'],
            [['name', 'price_base','brand_id'],'required'],
            [['price_discount','price_batch'],'default','value'=>'1.00'],
            [['color_list','style_list','space_list','price_list','place_list','sery_list','brand_id_for_price','brand_head','brand_name'],'safe'],
            [['gjj_code','factory_code','size','package'],'string','max'=>50],
	    	['app_return','default','value'=>'0'],
	    	[['supply_cycle'], 'string', 'max' => 20],
			[['top_surface','structure','filling','metals'], 'string', 'max' => 100],
	    	[['price_cost'],'match','pattern'=>'/^[0-9]{1,}\.{0,1}[0-9]{0,2}$/','message'=>'定制价折扣率的格式为1.11或0.99'],
            [['price_discount','price_batch'],'match','pattern'=>'/^[0-9]{1,}\.{0,1}[0-9]{0,3}$/','message'=>'定制价折扣率的格式为1.111或0.999'],
            [['QRcode'],'string','max'=>'200'],// '/^[\d]+\.[\d]{3}$/'
            [['update_at'],'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'type' => Yii::t('app','Type'),
            'name' => Yii::t('app','Sys Item Name'),
            'img_small_id' => Yii::t('app','Img Small ID'),
            'img_thumb_id' => Yii::t('app','Img Thumb ID'),
            'img_url_id' => Yii::t('app','Img Url ID'),
            'tips' => Yii::t('app','Tips'),
            'price_base' => Yii::t('app','Price Base'),
            'price_discount' => Yii::t('app','Price Discount'),
            'fabric_list' => Yii::t('app','Fabric List'),
            'material_list' => Yii::t('app','Material List'),
            'related_list' => Yii::t('app','Related List'),
            'app_return' => Yii::t('app','App Return'),
            'class_id' => Yii::t('app','Class ID'),
            'brand_id' => Yii::t('app','Brand ID'),
            'class1' => Yii::t('app','Class1'),
            'class2' => Yii::t('app','Class2'),
            'color_list' =>  Yii::t('app','Color List'),
            'style_list' =>  Yii::t('app','Style List'),
            'space_list' =>  Yii::t('app','Space List'),
            'price_list' =>  Yii::t('app','Price List'),
            'place_list' =>  Yii::t('app','Place List'),
            'sery_list' =>  Yii::t('app','Sery List'),
            'gjj_code' =>  Yii::t('app','Gjj Code'),
            'factory_code' =>  Yii::t('app','Factory Code'),
            'size' =>  Yii::t('app','Size'),
            'volume' =>  Yii::t('app','Volume'),
            'package' =>  Yii::t('app','Package'),
            'supply_cycle' => Yii::t('app','Supply Cycle'),
            'price_batch' => Yii::t('app','Price Batch'),
            'state_tree' => Yii::t('app','State Tree'),
			'top_surface'=>Yii::t('app','Item Top Surface'),
            'structure'=>Yii::t('app','Item Structure'),
            'filling'=>Yii::t('app','Item Filling'),
            'metals'=>Yii::t('app','Item Metals'),
            'brand_name'=>Yii::t('app','Brand Name'),
            'class_name'=>Yii::t('app','Class Name'),
            'price_cost'=>Yii::t('app','Price Cost'),
            'min_order_quantity'=>Yii::t('app', 'Min Order Quantity'),
            'introduction' => Yii::t('app', 'Item Introduction'),
            'bread_head' => Yii::t('app', '品牌分类'),
            'update_at'=>Yii::t('app','修改时间'),
            'unit_id'=>'单品单位',
            'unit_name'=>'单品单位'
        ];
    }

    public function getDefaultUrlImage()
    {
    	return $this->hasOne(Image::className(),['id'=>'img_url_id'])->from(['mainItemImgL'=>Image::tableName()]);
    }
    public function getDefaultThumbImage()
    {
    	return $this->hasOne(Image::className(),['id'=>'img_thumb_id'])->from(['mainItemImgM'=>Image::tableName()]);
    }
    public function getDefaultSmallImage()
    {
    	return $this->hasOne(Image::className(),['id'=>'img_small_id'])->from(['mainItemImgS'=>Image::tableName()]);
    }

    public function getClass_name()
    {
    	return $this->hasOne(GrpClass::className(),['id'=>'class_id']);
    }
    
    public function getUnit_name(){
        return $this->hasOne(GrpUnit::className(),['id'=>'unit_id']);
    }
    public function getBrand_name()
    {
    	return $this->hasOne(GrpBrand::className(),['id'=>'brand_id']);
    }
    public function getColor()
    {
        return $this->hasMany(GrpColor::className(), ['id'=>'color_id'])->viaTable(SysItemColor::tableName(),['item_id'=>'id']);
    }
    public function getStyle()
    {
        return $this->hasMany(GrpStyle::className(), ['id'=>'style_id'])->viaTable(SysItemStyle::tableName(),['item_id'=>'id']);
    }
    public function getSery()
    {
        return $this->hasMany(GrpSery::className(), ['id'=>'sery_id'])->viaTable(SysItemSery::tableName(),['item_id'=>'id']);
    }
    public function getSizeVolume()
    {
        return $this->hasMany(SysItemSize::className(), ['item_id'=>'id']);
    }

    public function getFabric()
    {
        return ArrayHelper::toArray(Fabric::findAll(explode(',', $this->fabric_list)));
    }
    public function getMaterial()
    {
        return ArrayHelper::toArray(Material::findAll(explode(',', $this->material_list)));
    }

    //扩展信息
    public function getExInfo()
    {
        $sql='SELECT grp_item_ex.`name`,sys_item_info_ex.item_ex_value AS value
            FROM sys_item_info_ex 
            LEFT JOIN grp_item_ex ON sys_item_info_ex.item_ex_id=grp_item_ex.id 
            WHERE sys_item_info_ex.item_id='.$this->id;
        return ActiveRecord::findBySql($sql)->asArray()->all();
    }
    public function getQRcode()
    {
        $url='https://test.jajahome.com/gjj/frontend/web/item/item-info?item_id='.$this->id;
        return Qr::generate($url);
    }
    public function getPreview()
    {
        return $this->hasMany(BaseSysPreview::className(), ['item_id'=>'id']);
    }
    //多角度图
    public function getLargePreview()
    {
        return $this->hasMany(Image::className(),['id'=>'img_url_id'])->viaTable(ItemPreview::tableName(), ['item_id'=>'id']);
    }
    public function getThumbPreview()
    {
        return $this->hasMany(Image::className(),['id'=>'img_thumb_id'])->viaTable(ItemPreview::tableName(), ['item_id'=>'id']);
    }
    public function getSmallPreview()
    {
        return $this->hasMany(Image::className(),['id'=>'img_small_id'])->viaTable(ItemPreview::tableName(), ['item_id'=>'id']);
    }

    public function getLargePreviewAngle()
    {
        $sql="SELECT sys_image.url FROM sys_image,`base_sys_preview` 
                LEFT JOIN base_sys_preview_angle ON base_sys_preview.id=base_sys_preview_angle.pid 
                WHERE base_sys_preview.item_id=".$this->id." AND sys_image.id=base_sys_preview_angle.img_url_id";
        return ArrayHelper::getColumn(self::findBySql($sql)->asArray()->all(),'url');
    }
    public function getThumbPreviewAngle()
    {
        $sql="SELECT sys_image.url FROM sys_image,`base_sys_preview` 
                LEFT JOIN base_sys_preview_angle ON base_sys_preview.id=base_sys_preview_angle.pid 
                WHERE base_sys_preview.item_id=".$this->id." AND sys_image.id=base_sys_preview_angle.img_thumb_id";
        return ArrayHelper::getColumn(self::findBySql($sql)->asArray()->all(),'url');
    }
    public function getSmallPreviewAngle()
    {
        $sql="SELECT sys_image.url FROM sys_image,`base_sys_preview` 
                LEFT JOIN base_sys_preview_angle ON base_sys_preview.id=base_sys_preview_angle.pid 
                WHERE base_sys_preview.item_id=".$this->id." AND sys_image.id=base_sys_preview_angle.img_small_id";
        return ArrayHelper::getColumn(self::findBySql($sql)->asArray()->all(),'url');
    }

    //获取coating
    public function getCoating()
    {
        return $this->hasMany(ItemPreview::className(), ['item_id'=>'id']);
    }

    public function getCreateUserName()
    {
    	return $this->hasOne(AdminInfo::className(), ['id'=>'create_uid']);
    }
    public function getUpdateUserName()
    {
    	return $this->hasOne(AdminInfo::className(), ['id'=>'update_uid']);
    }

	public static function find_sysitem_info($id){
    	return self::findOne(['id' => $id]);
    }
	public static function find_sysitem_info_brand($id){
    	return self::find()->with(['brand_name'])->where("sys_item.id={$id}")->one();
    }
    
    //后台显示图片需要
    public function getOneFabricImg()
    {
        $id=explode(',', $this->fabric_list);
        if(count($id)){
            return Image::find()->rightJoin('base_sys_fabric','sys_image.id=base_sys_fabric.img_small_id')->where(['base_sys_fabric.id'=>$id[0]])->one();
        }else{
            return null;
        }
    }
    public function getOneMaterialImg()
    {
        $id=explode(',', $this->material_list);
        if(count($id)){
            return Image::find()->rightJoin('base_sys_material','sys_image.id=base_sys_material.img_small_id')->where(['base_sys_material.id'=>$id[0]])->one();
        }else{
            return null;
        }
    }
    public function getOnePreviewImg()
    {
        return Image::find()->rightJoin('base_sys_preview','sys_image.id=base_sys_preview.img_tz_id')->where(['base_sys_preview.item_id'=>$this->id])->one();
    }
    
    public function getAllInfo($imageSize=[])
    {
        $arr=[
            'name'              =>['name'=>'产品名称','value'=>$this->name],
            'brandName'         =>['name'=>'产品品牌','value'=>!empty($this->brand_name)?$this->brand_name->name:null],
            'className'         =>['name'=>'产品分类','value'=>!empty($this->class_name)?$this->class_name->name:null],
            'factory_code'      =>['name'=>'厂家编码','value'=>$this->factory_code],
            'fabric'            =>['name'=>'产品面料','value'=>ArrayHelper::getColumn(ArrayHelper::toArray(Fabric::findAll(explode(',', $this->fabric_list))),'name')],
            'material'          =>['name'=>'产品材质','value'=>ArrayHelper::getColumn(ArrayHelper::toArray(Material::findAll(explode(',', $this->material_list))),'name')],
            'structure'         =>['name'=>'产品结构','value'=>$this->structure],
            'package'           =>['name'=>'包装件数','value'=>$this->package],
            'supply_cycle'      =>['name'=>'发货周期','value'=>$this->supply_cycle],
            'top_surface'       =>['name'=>'顶面工艺','value'=>$this->top_surface],
            'filling'           =>['name'=>'软体填充','value'=>$this->filling],
            'metals'            =>['name'=>'五金配件','value'=>$this->metals],
            'coatingList'       =>['name'=>'涂装工艺','value'=>ArrayHelper::getColumn(ArrayHelper::toArray($this->coating),'coating')],
            'sizeList'          =>['name'=>'尺寸体积','value'=>ArrayHelper::getColumn(ArrayHelper::toArray($this->sizeVolume),function($ele){
                                                                            $arr=[];$i=0;
                                                                            $ele['size']!=null&&$ele['size']!=''?$arr[$i++]=$ele['size']:'';
                                                                            $ele['volume']!=null&&$ele['volume']!=''?$arr[$i++]=$ele['volume']:'';
                                                                            return implode(':', $arr);
                                                                         })],
            'seryList'          =>['name'=>'产品系列','value'=>ArrayHelper::getColumn(ArrayHelper::toArray($this->sery),'name')],
            'colorList'         =>['name'=>'色彩分类','value'=>ArrayHelper::getColumn(ArrayHelper::toArray($this->color),'name')],
            'styleList'         =>['name'=>'样式风格','value'=>ArrayHelper::getColumn(ArrayHelper::toArray($this->style),'name')],
            'other'             =>[],
        ];
        
        $ex=self::getExInfo();
        if(!empty($ex)){
            foreach ($ex as $v)
            {
                $arr[$v['name']]=['name'=>$v['name'],'value'=>$v['value']];
            }
        }
        
        //1小图，2中图，3大图
        if(in_array(1, $imageSize)){
            $arr['other']['smallImg']=$this->defaultSmallImage->url;
            $arr['other']['smallPreviewList']=ArrayHelper::getColumn(ArrayHelper::toArray($this->smallPreview),'url');
            $arr['other']['smallPreviewAngleList']=$this->smallPreviewAngle;

        }
        if(in_array(2, $imageSize)){
            $arr['other']['thumbImg']=$this->defaultThumbImage->url;
            $arr['other']['thumbPreviewList']=ArrayHelper::getColumn(ArrayHelper::toArray($this->thumbPreview),'url');
            $arr['other']['thumbPreviewAngleList']=$this->thumbPreviewAngle;
        }
        if(in_array(3, $imageSize)){
            $arr['other']['largeImg']=$this->defaultUrlImage->url;
            $arr['other']['largePreviewList']=ArrayHelper::getColumn(ArrayHelper::toArray($this->largePreview),'url');

            $arr['other']['largePreviewAngleList']=$this->largePreviewAngle;
        }
        //$arr['other']['qrcode']=$this->getQRcode();
        $arr['other']['qrcode']=null;
        
        return $arr;
    }
    public static function generateQRcode($id){
    	$url='https://test.jajahome.com/gjj/frontend/web/item/item-info?item_id='.$id;
    	$QRcode = Qr::generate_admin($url,'item');
    	
    	Yii::$app->db->createCommand()->update('sys_item', ['QRcode'=>$QRcode],"id={$id}")->execute();   	
    }
}
